// 数据库操作
const mongoose = require('mongoose');
// 对象规则验证
const Joi = require('joi');

const {
	Schema
} = mongoose;

// 权限 一级
const authOneModel = new Schema({
		// 权限名称
		authName: {
			type: String,
			minlength: 2,
			maxlength: 10,
			required: true,
			unique: true
		},
		// 权限等级
		level: {
			type: Number,
			default: 1
		},
		// 路径
		path: {
			type: String,
			default: '',
			required: true
		},
		// 子权限
		children: [{
			type: mongoose.Schema.Types.ObjectId,
			ref: 'AuthTwo'
		}],
		// 图标
		icon: {
			type:String
		},
		// 创建时间
		createTime: {
			type: Date,
			default: Date.now
		}
}, {versionKey: false});

// 权限 二级
const authTwoModel = new Schema({
		// 权限名称
		authName: {
			type: String,
			minlength: 2,
			maxlength: 10,
			required: true,
			unique: true
		},
		// 权限等级
		level: {
			type: Number,
			default: 2
		},
		// 路径
		path: {
			type: String,
			default: '',
			required: true
		},
		// 子权限
		children: [{
			type: mongoose.Schema.Types.ObjectId,
			ref: 'AuthThree'
		}],
		
		// 创建时间
		createTime: {
			type: Date,
			default: Date.now
		}
}, {versionKey: false});

// 权限 三级
const authThreeModel = new Schema({
		// 权限名称
		authName: {
			type: String,
			minlength: 2,
			maxlength: 10,
			required: true,
			unique: true
		},
		// 权限等级
		level: {
			type: Number,
			default: 3
		},
		// 路径
		path: {
			type: String,
			default: '',
			required: true
		},
		// 创建时间
		createTime: {
			type: Date,
			default: Date.now
		}
}, {versionKey: false});

// 创建一级权限集合 
const AuthOne = mongoose.model('auth_one',authOneModel,'auth_one');
// 创建二级权限集合 
const AuthTwo = mongoose.model('auth_two',authTwoModel,'auth_two');
// 创建三级权限集合 
const AuthThree = mongoose.model('auth_three',authThreeModel,'auth_three');

// 权限数据格式校验
const validateAuth = auth => {
	// 定义对象验证规则
	const schema = {
		authName: Joi.string().min(2).max(10).required().error(new Error('权限名称字数应在2-15之间')),
	};
	// 验证
	return Joi.validate(auth, schema, {
		// 检测到所有错误
		abortEarly: false,
		// 允许对象包含被忽略的未知键
		allowUnknown: true
	});
}


// 导出对象
module.exports = {
	AuthOne, 
	AuthTwo, 
	AuthThree,
	validateAuth
};
